//
// Created by wll on 2021/11/11.
//

#include "LanguageParsers.h"
#include "WllSingleton.h"
#include "CompilerManager.h"
#include "Compiler.h"
#include <fstream>
#include "WllTrace.h"

LanguageParsers::LanguageParsers(Compiler* compiler) : languages(compiler->languages)
{
    this->compiler = compiler;
}

bool LanguageParsers::Load()
{
    std::string cache_file_name = GetCacheFileName();

    if (access(cache_file_name.c_str(),R_OK) == 0)
    {
        INFO("[" << cache_file_name << "] disk cache hint");

        std::ifstream input(cache_file_name);
        if (!input)
        {
            INFO("open [" << cache_file_name << "] failed");
            return false;
        }

        INFO("loading [" << cache_file_name << "] from disk");
        bool result = Load(input);
        if (result)
        {
            INFO("[" << cache_file_name << "] loaded SUCCESS");
        }
        else
        {
            INFO("[" << cache_file_name << "] loaded FAILED");
        }

        return result;
    }
    else
    {
        INFO("[" << cache_file_name << "] disk cache NOT hint");
        return false;
    }
}

bool LanguageParsers::Save()
{
    std::string cache_file_name = GetCacheFileName();
    std::ofstream output(cache_file_name);
    if (!output)
    {
        INFO("open [" << cache_file_name << "] failed");
        return false;
    }
    INFO("saving " << cache_file_name);
    bool result = Save(output);
    INFO(cache_file_name << " saved");

    return result;
}

std::string LanguageParsers::GetCacheFileName()
{
    return CompilerManager::GetCacheBaseDir() + "/" + this->compiler->compiler_id.compiler_id + "." + this->GetParserType();
}